import {
    phoneLogin,
    sendCode
} from "../../request/api"
const app = getApp();
Page({
    data: {
        phone: '',
        code: '',
        countdown: 60,
        isCounting: false,
        loading: false
    },

    // 手机号输入
    handlePhoneInput(e) {
        this.setData({
            phone: e.detail.value
        });
    },

    // 验证码输入
    handleCodeInput(e) {
        this.setData({
            code: e.detail.value
        });
    },

    // 发送验证码
    async getVerificationCode() {
        const { phone, isCounting } = this.data;

        if (!phone) {
            wx.showToast({ title: '请输入手机号', icon: 'none' });
            return;
        }

        if (isCounting) return;

        this.setData({ isCounting: true });

        let res = await sendCode({
            phone
        });
        if (res.code === 200) {
            wx.showToast({ title: '验证码已发送', icon: 'none' });
            this.startCountdown();
        } else {
            wx.showToast({ title: res.msg || '验证码发送失败', icon: 'none' });
            this.setData({ isCounting: false });
        }
    },

    // 倒计时
    startCountdown() {
        let timer = setInterval(() => {
            if (this.data.countdown <= 0) {
                clearInterval(timer);
                this.setData({
                    countdown: 60,
                    isCounting: false
                });
                return;
            }
            this.setData({
                countdown: this.data.countdown - 1
            });
        }, 1000);
    },

    // 登录提交
    async handleLoginSubmit() {
		const { phone, code } = this.data;
		const openid = app.globalData.openid;
        if (!phone) {
            wx.showToast({ title: '请输入手机号', icon: 'none' });
            return;
        }

        if (!code) {
            wx.showToast({ title: '请输入验证码', icon: 'none' });
            return;
        }

        this.setData({ loading: true });
        let res = await phoneLogin({
            phone:  phone,
            code:code,
            openid:openid
        });
        if (res.code == 200) {
            wx.setStorageSync('access_token', `Bearer ${res.data.token}`);
            wx.setStorageSync('userInfo', res.data.userInfo);
            wx.showToast({ title: '登录成功', icon: 'success' });
            setTimeout(() => {
                wx.switchTab({
                    url: '/pages/home/home'
                });
            }, 1500);
        }else {
            wx.showToast({ title: res.msg || '登录失败', icon: 'none' });
        }
    }
});